#include <stdlib.h>
#include <stdio.h>
#include <signal.h>
#include <execinfo.h>
#include <readline/readline.h>
#include <math.h>
#include <assert.h>
#include <getopt.h>
#include <unistd.h>
#include <sys/wait.h>

#include "ic.h"

#define USAGE "Usage: icclient [<options>] \n"					\
	"-h - show this help\n"										\
	"-b - get report, credentials needed for this operation\n"	\
	"-r <station> - play radio"											\
	"-l <login> - login \n"										\
	"-p <password> - password \n"								\
	"-s - show radio list\n"									\

int main(int argc, char *argv[])
{
	char opt = -1;
	int get_balance = 0;
	int get_list = 0;
	char *login = NULL;
	char *pass = NULL;
	char *station = NULL;

	while( (opt = getopt(argc, argv, "hsbp:r:l:")) > 0){
		switch(opt){
		case 'b':
			get_balance = 1;
			break;
		case 'p':
			pass = optarg;
			break;
		case 'r':
			station = optarg;
			break;
		case 's':
			get_list = 1;
			break;
		case 'h':
			printf(USAGE);
			return 0;
		case 'l':
			login = optarg;
			break;
		}
	}

	if(!get_balance && !get_list && !station)
		printf(USAGE);

	if(get_balance){
		if(!login)
			login = "deflogin";
		if(!pass)
			pass = "defpassword";
		
		GError *error = NULL;
		report_t rep;
		gboolean res = ic_get_report(login, pass, &rep, &error);
		if(res == TRUE){
			printf("Balance = %0.2f\nTraffic = %0.3f\nStatus = %s\nExpired on = %s\n", 
				   rep.balance, rep.traffic, rep.blocked ? "Blocked":"Ok", rep.expired_on);
		}
		if(error){
			puts(error->message);
		}
	}

	if(get_list){
		int i=0;
		char **list = ic_radio_get_list(NULL);
		for(char **it = list; *it; it++, i++){
			printf("%3d %s \n", i, *it);
		}
	}

	if(station){
		GError *error = NULL;
		int pid = ic_radio_play(station, "mplayer", &error);
		if(pid < 0 && error){
			puts(error->message);
		}
		waitpid(pid, NULL, 0);
	}

	return 0;
}
